const socket = io("http://localhost:3000");
const messagesBox = document.getElementById("message_box");
const messageForm = document.getElementById("send_box");
const messageInput = document.getElementById("message_input");

const useName = prompt("您的姓名是：");
appendMessage("你已经加入聊天系统");
socket.emit("new-user", useName); // 发送姓名到执行的socketio接收器中

// 开启chat-message类消息监听
socket.on("chat-message", (data) => {
  console.log(data);
  appendMessage(`用户${data.name}说了: ${data.message}`);
});

// 开启user-connected类消息监听
socket.on("user-connected", (data) => {
  appendMessage(`${data} 已连接`);
});

// 开启user-disconnected类消息监听
socket.on("user-disconnected", (data) => {
  appendMessage(`${data} disconnected`);
});

// 为表单绑定事件，并发送相应消息给socketio服务
messageForm.addEventListener("submit", (e) => {
  e.preventDefault();
  const message = messageInput.value;
  appendMessage(`您发了：${message}`);
  socket.emit("send-chat-message", message); // 向socket.io服务器发送消息
  messageInput.value = "";
});

// 显示消息
function appendMessage(message) {
  const messageEl = document.createElement("div");
  messageEl.innerText = message;
  messagesBox.append(messageEl);
}
